#include <QCompleter>
#include "gui/transactionviewadddialog.h"
#include "core/constants.h"


QComboBox *TransactionViewAddDialog::createItemBox()
{
    int i;
    ItemController *ctrl = new ItemController;
    QList<BaseModel *> models = ctrl->getAll();
    ItemModel *item;

    QString name;
    QStringList nameList;
    QCompleter *completer;

    QComboBox *comboBox = new QComboBox;

    comboBox->addItem("", ""); // This will be the default choice
    for (i = 0; i < models.length(); i++) {
        item = (ItemModel *) models.at(i);
        name = QString("%1 %2").arg(item->getName(), item->getCode());
        nameList << name;
        comboBox->addItem(name, item->getID());
    }

    completer = new QCompleter(nameList, this);
    comboBox->setEditable(true);
    comboBox->setCompleter(completer);

    delete ctrl;
    return comboBox;
}

QComboBox *TransactionViewAddDialog::createStockBox()
{
    int i;
    StockController *ctrl = new StockController;
    QList<BaseModel *> models = ctrl->getAll();
    StockModel *stock;
    QStringList serialList;
    QCompleter *completer;
    QComboBox *comboBox = new QComboBox;

    comboBox->addItem("", ""); // This will be the default choice
    for (i = 0; i < models.length(); i++) {
        stock = (StockModel *) models.at(i);
        stocks.append(stock);
        serialList << stock->getSerial();
        comboBox->addItem(stock->getSerial(), stock->getID());
    }

    completer = new QCompleter(serialList, this);
    comboBox->setEditable(true);
    comboBox->setCompleter(completer);

    delete ctrl;
    return comboBox;
}

QGroupBox *TransactionViewAddDialog::createStockArea()
{
    QGroupBox *stockGroupBox = new QGroupBox("Items and Stocks in this Transaction");
    stockMainLayout = new QVBoxLayout;
    stockButtonLayout = new QGridLayout;

    // Second column (comboboxes) should occupy all free space
    stockButtonLayout->setColumnStretch(1, 1);

    slist = new ShinyList;
    stockMainLayout->addWidget(slist);

    itemLabel = new QLabel("Item: ");
    stockButtonLayout->addWidget(itemLabel, 0, 0);

    itemBox = this->createItemBox();
    stockButtonLayout->addWidget(itemBox, 0, 1);

    stockLabel = new QLabel("Stock: ");
    stockButtonLayout->addWidget(stockLabel, 1, 0);

    stockBox = this->createStockBox();
    stockButtonLayout->addWidget(stockBox, 1, 1);

    stockMainLayout->addLayout(stockButtonLayout);

    stockControlButtonsBox = new QDialogButtonBox;
    stockControlButtonsBox->addButton("Add", QDialogButtonBox::AcceptRole);
    stockControlButtonsBox->addButton("Clear All", QDialogButtonBox::RejectRole);
    stockMainLayout->addWidget(stockControlButtonsBox);
    stockGroupBox->setLayout(stockMainLayout);

    return stockGroupBox;
}

QComboBox *TransactionViewAddDialog::createCustomerBox()
{
    int i;
    CustomerController *ctrl = new CustomerController;
    QList<BaseModel *> models = ctrl->getAll();
    CustomerModel *customer;
    QStringList nameList;
    QCompleter *completer;
    QComboBox *comboBox = new QComboBox;

    comboBox->addItem("", ""); // This will be the default choice
    for (i = 0; i < models.length(); i++) {
        customer = (CustomerModel *) models.at(i);
        customers.append(customer);
        nameList << customer->getName();
        comboBox->addItem(customer->getName(), customer->getID());
    }

    completer = new QCompleter(nameList, this);
    completer->setCaseSensitivity(Qt::CaseInsensitive);
    comboBox->setEditable(true);
    comboBox->setCompleter(completer);

    delete ctrl;
    return comboBox;
}

void TransactionViewAddDialog::initUiComponents()
{
    QFont font;
    mainLayout = new QVBoxLayout;
    gridLayout = new QGridLayout;
    gridLayout->setColumnStretch(1, 1);

    headerLabel = new QLabel("Add a Transaction");
    font = headerLabel->font();
    font.setPointSize(font.pointSize() + HEADER_UPSIZE);
    headerLabel->setFont(font);
    mainLayout->addWidget(headerLabel);

    subHeaderLabel = new QLabel("Enter your new Transaction's details.");
    mainLayout->addWidget(subHeaderLabel);
    mainLayout->addWidget(new SeparatorWidget);

    customerLabel = new QLabel("Customer:");
    gridLayout->addWidget(customerLabel, 0, 0);
    customerBox = this->createCustomerBox();
    gridLayout->addWidget(customerBox, 0, 1);

    paidLabel = new QLabel("Payment Status: ");
    gridLayout->addWidget(paidLabel, 1, 0);
    paidBox = new QComboBox;
    paidBox->addItem("Unpaid", "UNPAID");
    paidBox->addItem("Paid", "PAID");
    gridLayout->addWidget(paidBox, 1, 1);

    deliveryStatusLabel = new QLabel("Delivery Status:");
    gridLayout->addWidget(deliveryStatusLabel, 2, 0);
    deliveryStatusBox = new QComboBox;
    deliveryStatusBox->addItem("Waiting on Stocks", "RECORDED");
    deliveryStatusBox->addItem("Waiting on Delivery", "STOCKED");
    deliveryStatusBox->addItem("Delivered", "DELIVERED");
    gridLayout->addWidget(deliveryStatusBox, 2, 1);

    mainLayout->addLayout(gridLayout);

    stockGroupBox = this->createStockArea();
    mainLayout->addWidget(stockGroupBox);

    validityBox = new QCheckBox;
    validityBox->setText("Valid");
    mainLayout->addWidget(validityBox);
    validityBox->hide();

    mainLayout->addWidget(new SeparatorWidget);
    buttonBox = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Cancel);
    mainLayout->addWidget(buttonBox);

    this->setLayout(mainLayout);
}

void TransactionViewAddDialog::onStockClearAllClicked()
{
    QMessageBox msgBox(this);
    msgBox.setWindowTitle("Confirm stock removal");
    msgBox.setText("You are about to remove all attached stocks from this transaction.");
    msgBox.setInformativeText("Are you sure you want to clear all stocks?");
    msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    msgBox.setDefaultButton(QMessageBox::No);
    msgBox.setIcon(QMessageBox::Question);
    msgBox.exec();
}

CustomerModel *TransactionViewAddDialog::getCustomer()
{
    int index = this->customerBox->currentIndex();
    int i;
    qDebug() << "TransactionViewAddDialog: Selected index: " << index;

    qDebug() << "Customers:";
    for (i = 0; i < customers.length(); i++) {
        qDebug() << i << " : " << customers.at(i)->getName();
    }

    // +1 to account for the empty list item as the zeroth element
    if (index == 0 || index == (customers.length() + 1)) {
        qDebug() << "TransactionViewAddDialog: No customer selected, returning NULL!";
        return NULL;
    }

    return customers.at(index - 1);
}

QString TransactionViewAddDialog::getDeliveryStatus()
{
    QString statuses[] = {
        "RECORDED",
        "STOCKED",
        "DELIVERED"
    };

    return statuses[this->deliveryStatusBox->currentIndex()];
}

void TransactionViewAddDialog::onStockAddClicked()
{
    bool complete = true;
    TransactionModel *transaction;

    if (!complete) {
        QMessageBox::critical(this,
                          "Incomplete Stock Data",
                          "An Item type and Stock serial number must be specified "
                          "in order to add a Stock to this Transaction.");
        return;
    }
}

TransactionModel *TransactionViewAddDialog::getTransaction()
{
    return this->transaction;
}

void TransactionViewAddDialog::onSaveButtonClicked()
{
    bool complete = true;

    complete &= this->customerBox->currentIndex() > 0; // Must select a customer

    if (!complete) {
        QMessageBox::critical(this,
                          "Incomplete Transaction Data",
                          "You must fill in all fields and add at least one stock "
                          "before you can save this Transaction.");
        return;
    }

    transaction = new TransactionModel;
    transaction->setCustomer(this->getCustomer());
    transaction->setDeliveryStatus(this->getDeliveryStatus());
    transaction->setPaid(this->paidBox->currentIndex() == 1);
    transaction->setValid(true);
    transaction->updateLastModificationTime();

    this->transaction = transaction;
    this->accept();
}

void TransactionViewAddDialog::initSignalsAndSlots()
{
    connect(this->buttonBox, SIGNAL(accepted()),
            this, SLOT(onSaveButtonClicked()));
    connect(this->buttonBox, SIGNAL(rejected()),
            this, SLOT(reject()));
    connect(this->stockControlButtonsBox, SIGNAL(rejected()),
            this, SLOT(onStockClearAllClicked()));
    connect(this->stockControlButtonsBox, SIGNAL(accepted()),
            this, SLOT(onStockAddClicked()));
}

TransactionViewAddDialog::TransactionViewAddDialog(QWidget *parent) :
    QDialog(parent)
{
    this->setWindowTitle("Add Transaction");
    this->setMinimumWidth(640);
    this->initUiComponents();
    this->initSignalsAndSlots();
    this->transaction = NULL;
}
